package com.cangxuan.app.utils;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import com.alibaba.fastjson.JSONObject;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;

/**
 * HTTP请求工具类
 */
public class HttpUtils {

//    public static String host = "http://192.168.138.1:8081";
//    public static String host = "http://192.168.1.43:81";
    public static String host = "https://www.cangxuan.vip";

    /**
     * 以GET方式请求接口
     *
     * @param spec 接口地址
     * @return
     */
    public static String get(String spec) {
        return get(spec, null);
    }

    /**
     * 以GET方式请求接口
     *
     * @param spec 接口地址
     * @param headers 请求头
     * @return
     */
    public static String get(String spec, Map<String, String> headers) {
        StringBuilder stringBuilder = new StringBuilder();
        //定义字节输入流
        InputStream inputStream = null;
        //定义一个字符转换流
        InputStreamReader inputStreamReader = null;
        //定义一个字符输入缓冲流
        BufferedReader bufferedReader = null;
        try {
            if (!spec.startsWith("http")) spec = host + spec;
            //创建一个URL对象
            URL url = new URL(spec);
            //得到一个URL连接器
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            if (headers != null)
                for (String key : headers.keySet()) httpURLConnection.setRequestProperty(key, headers.get(key));
            //得到字节输入流
            inputStream = httpURLConnection.getResponseCode() == HttpURLConnection.HTTP_OK
                    ? httpURLConnection.getInputStream() : httpURLConnection.getErrorStream();
            //创建一个字符转换流
            inputStreamReader = new InputStreamReader(inputStream);
            //创建一个字符输入缓冲流
            bufferedReader = new BufferedReader(inputStreamReader);
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                stringBuilder.append(line);
            }
        } catch (Exception exception) {
            exception.printStackTrace();
        } finally {
            try {
                if (bufferedReader != null) bufferedReader.close();
                if (inputStreamReader != null) inputStreamReader.close();
                if (inputStream != null) inputStream.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return stringBuilder.toString();
    }

    /**
     * 以POST方式请求接口
     *
     * @param spec 接口地址
     * @param body body参数
     * @return2
     */
    public static String post(String spec, String body) {
        return post(spec, null, body, null);
    }

    /**
     * 以POST方式请求接口
     *
     * @param spec 接口地址
     * @param headers 请求头
     * @param body body参数
     * @return
     */
    public static String post(String spec, Map<String, String> headers, String body) {
        return post(spec, headers, body, null);
    }

    private static String rsaPublicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAhIUc4yipstvb0Rhoblpke107VgZZob53o5u2RPkS6kdrwHg3E/7Dk4dlg7bGhbiyZVjsYBPn5L2uGbCRsIm4aJ6zlJzWAPEP7YZ9Q+gnjxQ3iXwpqyBkfHnfCFvDpZ867pstsQGMv1i3eFAhYoX55iR6NG1KYDGrH7SR7CphQVSLmycbKQwVSqcAbQOC5L99VSTGH6u37cEk/R3oobKFtsn6aQ8HwZHn7jKcPIBnokeW7B/wJWlINoB8jLD2FFpGigV78O1+3Hvlgo0uC/U/F9mm7o3ET2td9ys/Z0tDHBiCeR3uDI/8BoWtJtPR6U9g3DZVwV2F6xAALCufZZIyKwIDAQAB";

    /**
     * 以POST方式请求接口
     *
     * @param spec 接口地址
     * @param headers 请求头
     * @param body body参数
     * @return
     */
    public static String post(String spec, Map<String, String> headers, String body, String other) {
        StringBuilder stringBuilder = new StringBuilder();
        //定义字节输出流
        OutputStream outputStream = null;
        //定义字节输出转换流
        OutputStreamWriter outputStreamWriter = null;
        //定义字节输入流
        InputStream inputStream = null;
        //定义一个字符转换流
        InputStreamReader inputStreamReader = null;
        //定义一个字符输入缓冲流
        BufferedReader bufferedReader = null;
        try {
            if (!spec.startsWith("http")) spec = host + spec;
            //创建一个URL对象
            URL url = new URL(spec);
            //得到一个URL连接器
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            if (headers != null)
                for (String key : headers.keySet()) httpURLConnection.setRequestProperty(key, headers.get(key));
            //在这里添加POST请求
            httpURLConnection.setRequestMethod("POST");     //设置HTTP的请求方式为：POST
            httpURLConnection.setDoOutput(true);    //将HTTP的请求设置为可允许操作输出流
            httpURLConnection.setRequestProperty("Content-Type", "application/json;charset=UTF-8"); //设置输出内容的格式与编码
            httpURLConnection.setConnectTimeout(60000);
            httpURLConnection.setReadTimeout(60000);
            if (body != null && !body.equals("")) {
                //对body进行加密
                String aesKeyDecrypt = RandomUtils.getRandomString(16);
                //对aesKeyDecrypt非对称加密
                String aesKeyEncrypt = SecurityUtils.encryptRSA(rsaPublicKey, aesKeyDecrypt);
                //对body进行对称加密
                JSONObject jsonBody = new JSONObject();
                jsonBody.put("key", aesKeyEncrypt);
                jsonBody.put("data", SecurityUtils.encryptAES(aesKeyDecrypt, body));
                if (other != null) jsonBody.put("other", other);
                Log.i("Post的url:", spec);
                Log.i("Post的body:",jsonBody.toJSONString());
                //在body中放置参数
                //先获取输出流
                outputStream = httpURLConnection.getOutputStream();
                //创建一个字符输出转换流
                outputStreamWriter = new OutputStreamWriter(outputStream);
                outputStreamWriter.write(jsonBody.toJSONString());
                outputStreamWriter.close();
            }

            //得到字节输入流
            inputStream = httpURLConnection.getResponseCode() == HttpURLConnection.HTTP_OK
                    ? httpURLConnection.getInputStream() : httpURLConnection.getErrorStream();
            //创建一个字输入符转换流
            inputStreamReader = new InputStreamReader(inputStream);
            //创建一个字符输入缓冲流
            bufferedReader = new BufferedReader(inputStreamReader);
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                stringBuilder.append(line);
            }
        } catch (Exception exception) {
            exception.printStackTrace();
        } finally {
            try {
                if (bufferedReader != null) bufferedReader.close();
                if (inputStreamReader != null) inputStreamReader.close();
                if (inputStream != null) inputStream.close();
                if (outputStreamWriter != null) outputStreamWriter.close();
                if (outputStream != null) outputStream.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return stringBuilder.toString();
    }

    /**
     * 下载文件
     *
     * @param spec 文件地址
     * @param path 下载位置，包括路径+文件名
     * @return 是否下载成功
     */
    public static boolean download(String spec, String path) {
        //定义字节输入流
        InputStream inputStream = null;
        //定义一个字节输出流
        FileOutputStream fileOutputStream = null;
        //定义一下文件输出流
        BufferedOutputStream bufferedOutputStream = null;
        try {
            if (!spec.startsWith("http")) spec = host + spec;
            //创建一个URL对象
            URL url = new URL(spec);
            //得到一个URL连接器
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            //得到字节输入流
            inputStream = httpURLConnection.getResponseCode() == HttpURLConnection.HTTP_OK
                    ? httpURLConnection.getInputStream() : httpURLConnection.getErrorStream();
            //文件所在目录
            File directory = new File(path.substring(0, path.lastIndexOf("/")));
            if (!directory.exists()) directory.mkdirs();
            File file = new File(path);
            //创建位图对象
            Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
            //创建文件输出流
            fileOutputStream = new FileOutputStream(file);
            //创建输出缓冲流
            bufferedOutputStream = new BufferedOutputStream(fileOutputStream);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bufferedOutputStream);
            bufferedOutputStream.flush();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (bufferedOutputStream != null) bufferedOutputStream.close();
                if (fileOutputStream != null) fileOutputStream.close();
                if (inputStream != null) inputStream.close();
            } catch (Exception exception) {
                exception.printStackTrace();
            }
        }
        return false;
    }
}
